package com.proton.carepatchtemp.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.ui.ToastUtils;

import java.io.File;

public class HealthTipsActivity extends BaseActivity {

    private static final String APP_CACAHE_DIRNAME = "mywebcache";
    private ImageButton mBtnBack;
    private String url;
    private WebView mWvHealthTips;
    /**
     * 健康贴士
     */
    private TextView mTvWebTitle;

    @Override
    public void dealEvent(MainEvent event) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_tips);
        initView();
        if (TextUtils.isEmpty(getIntent().getStringExtra(Extras.MSG_HEALTH_TIPS_URL))) {
            finish();
        } else {
            url = getIntent().getStringExtra(Extras.MSG_HEALTH_TIPS_URL);
        }

        mTvWebTitle.setText(getIntent().getExtras().getString(Extras.WEB_TITLE));

        initWebView();
        setWebViewLoadingView();
        setListener();

//        // 开启 localStorage
//        mWvHealthTips.getSettings().setDomStorageEnabled(true);
//        // 设置支持javascript
//        mWvHealthTips.getSettings().setJavaScriptEnabled(true);
//        // 启动缓存
//        mWvHealthTips.getSettings().setAppCacheEnabled(true);
//        // 设置缓存模式
//        mWvHealthTips.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//        //使用自定义的WebViewClient
//        mWvHealthTips.setWebViewClient(new WebViewClient() {
//            //覆盖shouldOverrideUrlLoading 方法
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                return false;
//            }
//        });
//        mWvHealthTips.loadUrl(url);

    }

    @Override
    protected void setListener() {
        mBtnBack.setOnClickListener(v -> {
            clearWebViewCache();
            finish();
        });
    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
        mWvHealthTips = findViewById(R.id.wv_health_tips);
        mTvWebTitle = findViewById(R.id.tv_web_title);
    }

    // 覆盖onKeydown 添加处理WebView 界面内返回事件处理
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWvHealthTips.canGoBack()) {
            mWvHealthTips.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearWebViewCache();
    }

    private void initWebView() {

        mWvHealthTips.getSettings().setJavaScriptEnabled(true);
        mWvHealthTips.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWvHealthTips.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能
        mWvHealthTips.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        mWvHealthTips.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
// String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;

//设置数据库缓存路径
        mWvHealthTips.getSettings().setDatabasePath(cacheDirPath);
//设置 Application Caches 缓存目录
        mWvHealthTips.getSettings().setAppCachePath(cacheDirPath);
//开启 Application Caches 功能
        mWvHealthTips.getSettings().setAppCacheEnabled(true);
    }

    private void setWebViewLoadingView() {
        mWvHealthTips.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {

                LogUtils.i("onLoadResource url=" + url);

                super.onLoadResource(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webview, String url) {

                LogUtils.i("intercept url=" + url);

                webview.loadUrl(url);

                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                LogUtils.e("onPageStarted");

//                rl_loading.setVisibility(View.VISIBLE); // 显示加载界面
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                String title = view.getTitle();
                LogUtils.e("onPageFinished WebView title=" + title);

//                tv_topbar_title.setText(title);
//                tv_topbar_title.setVisibility(View.VISIBLE);

//                rl_loading.setVisibility(View.GONE); // 隐藏加载界面
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                LogUtils.e("onReceivedError:   failingUrl = " + failingUrl + "\n" + description);
                ToastUtils.e(description);
            }
        });

        mWvHealthTips.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

                LogUtils.e("onJsAlert " + message);

                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

                result.confirm();

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

                LogUtils.e("onJsConfirm " + message);

                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {

                LogUtils.e("onJsPrompt " + url);

                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });

        mWvHealthTips.loadUrl(url);
    }

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {

        //清理Webview缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebView 缓存文件
        File appCacheDir = new File(getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME);
        LogUtils.e("appCacheDir path=" + appCacheDir.getAbsolutePath());

        File webviewCacheDir = new File(getCacheDir().getAbsolutePath() + "/webviewCache");
        LogUtils.e("webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }
    }

    /**
     * 递归删除 文件/文件夹
     */
    public void deleteFile(File file) {

        LogUtils.d("delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            LogUtils.e("delete file no exists " + file.getAbsolutePath());
        }
    }

    @Override
    public void onEventMainThread(MainEvent event) {

    }
}


